package com.uwo.commons.kits;

import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 正则匹配
 * @author hao.yan
 */
public class MatcherKits {

    // 手机号正则
    public static final String mobile = "^(1[3-9][0-9])\\d{8}$";

    // 邮箱正则
    public static final String email = "^([a-z0-9A-Z]+[-|\\.]?)+[a-z0-9A-Z]@([a-z0-9A-Z]+(-[a-z0-9A-Z]+)?\\.)+[a-zA-Z]{2,}$";

    // 路径地址
    public static final String url = "http(s)?://([\\w-]+\\.)+[\\w-]+(/[\\w- ./?%&=]*)?";

    /**
     * 正则匹配
     * @param pattern
     * @param context
     * @return
     */
    public static boolean matches(String pattern, String context){
        // 编译正则表达式
        Pattern p = Pattern.compile(pattern);
        Matcher matcher = p.matcher(String.valueOf(context));
        // 字符串是否与正则表达式相匹配
        return matcher.matches();
    }

    public static String value(String pattern, String context){
        List<String> values = values(pattern, context);
        return (values.size() > 0)?values.get(0):null;
    }

    public static List<String> values(String pattern, String context){
        List<String> values = new ArrayList<String>();
        Pattern p = Pattern.compile(pattern);
        Matcher matcher = p.matcher(context);
        while(matcher.find())
            values.add(matcher.group());
        return values;
    }

}
